<?php


namespace app\admin\controller;


use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;

class JwtAuth
{
    private $token;
    private $user_id;
    private $secrect="#awadakvcabzijvnjmzbhwlfceivsejvsuvrgdfsas";
    private $aud="tpv.x";
    private $iss="tpv.x";
    private $decodeToken;
    /**
     * JTW句柄
     * @var
     */
    private static $instance;

    public static function getInstance(){
        if (is_null(self::$instance)){
            self::$instance =new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
    }

    private function __clone(){

    }

    public function getToken(){
        return (string)$this->token;
    }

    public function setToken($token){
        $this->token = $token;

        return $this;
    }

    public function setUid($user_id){
        $this->user_id =$user_id;
        return $this;
    }

    public function encode(){
        $time= time();
        $this->token = (new Builder())
            ->setHeader('alg','HS256')
            ->setIssuer($this->iss)
            ->setAudience($this->aud)
            ->setIssuedAt($time)
            ->setExpiration($time+3600)
            ->set('user_id',$this->user_id)
            ->sign(new Sha256(), $this->secrect)
            ->getToken();
        return $this;
    }

    /**
     * @return \Lcobucci\JWT\Token
     */
    public function decode(){
        if (!$this->decodeToken){
            $this->decodeToken = (new Parser())->parse((string)$this->token);
            $this->user_id = $this->decodeToken->getClaim('user_id');
        }

        return $this->decodeToken;
    }

    /**
     * @return bool
     */
    public function validate(){
        $data = new ValidationData();
        $data->setIssuer($this->iss);
        $data->setAudience($this->aud);

        return $this->decode()->validate($data);
    }

    /**
     * @return bool
     */
    public function verify(){
        $result = $this->decode()->verify(new Sha256() , $this->secrect);
        return $result;
    }

    public function getUid(){
        return (new Parser())->parse((string)$this->token)->getClaim('user_id');
    }



}
